package com.thinkit.bigdata.core.util.dataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

/**
 * 配置多数据源
 *
 * @author huzenghui
 * @date 2019/10/28
 */
public class DynamicDataSource extends AbstractRoutingDataSource {
    private static final Logger LOGGER = LoggerFactory.getLogger(DynamicDataSource.class);

    // 配置文件 applicationContext-mybatis.xml 中设置的两个"key"名称
    public static final String DATASOURCE_QUALITY = "dataSource_quailty";
    public static final String DATASOURCE_TAG = "dataSource_tag";

    // 本地线程
    public static final ThreadLocal<String> contextHolder = new ThreadLocal<>();

    public static void setCustomerType(String customerType) {
        // 把当前请求的参数，存入当前线程，这个参数是我们定义的DATASOURCE_A或DATASOURCE_B
        LOGGER.info("当前切换的数据源 = {}", customerType);
        contextHolder.set(customerType);
    }

    public static String getCustomerType() {
        return contextHolder.get();
    }

    /**
     * 切换默认数据源
     */
    public static void clearCustomerType() {
        contextHolder.remove();
    }

    @Override
    protected Object determineCurrentLookupKey() {
        return getCustomerType();
    }
}
